//
//  DataManager.m
//  HuaWan
//
//  Created by HuaWan  on 2023.
//  Copyright © 2023 HuaWan . All rights reserved.
//

#import "DataManager.h"

@interface DataManager ()

@property (nonatomic, strong) YTKKeyValueStore *store;

@end

@implementation DataManager

+ (instancetype)shareInstance {
    static DataManager *_manager = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _manager = [[self alloc] init];
    });
    return _manager;
}

#pragma mark - 公共数据

//获取随机guid guid一般是32位的，生成规则和随机数不同
- (NSString*)getGuid {
    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
    CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);
    CFRelease(uuid_ref);
    NSString *uuid = [NSString stringWithString:(__bridge NSString*)uuid_string_ref];
    CFRelease(uuid_string_ref);
    return [uuid stringByReplacingOccurrencesOfString:@"-" withString:@""];
}

- (NSArray *)tableAry {
    return @[@"tea",@"type"];
}

- (NSArray *)typeTitles {
    NSArray *ary = @[@"一点点",@"喜茶",@"奈雪",@"茶百道",@"霸王茶姬",@"茶颜悦色",@"蜜雪",@"茉酸奶",@"KOI",@"自定义"];
    return ary;
}

- (NSArray *)typeIcos {
    NSArray *ary = @[@"yidiandian",@"xicha",@"naixue",@"chabaidao",@"bawang",@"chayan",@"mixue",@"mosuannai",@"ko",@"zidingyi"];
    return ary;
}

#pragma mark - 初始化

- (void)initTable {
    if (![[[NSUserDefaults standardUserDefaults] objectForKey:@"isSecond"] boolValue]) {
        //第一次
        [self.tableAry enumerateObjectsUsingBlock:^(NSString *name, NSUInteger idx, BOOL * _Nonnull stop) {
            //创建表
            [self.store createTableWithName:[NSString stringWithFormat:@"%@_table",name]];
        }];
        
        [self.typeTitles enumerateObjectsUsingBlock:^(NSString *title, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString *ico = self.typeIcos[idx];
            HWTypeModel *typeModel = [HWTypeModel new];
            typeModel.name = title;
            typeModel.ico = ico;
            typeModel.isCustom = NO;
            [self addTypeDataWithModel:typeModel];
        }];
        
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:@"YES" forKey:@"isSecond"];
        [userDefaults synchronize];
    }
}

#pragma mark - 添加数据

- (void)addTeaDataWithModel:(HWTeaModel *)model {
    if (model) {
        NSString *teaId = [self getGuid];
        if (model.teaId.length > 0) {
            teaId = model.teaId;
        }
        
        model.teaId = teaId;
        
        NSDictionary *dic = model.mj_keyValues;
        [self.store putObject:dic withId:teaId intoTable:[NSString stringWithFormat:@"%@_table",@"tea"]];
    }
}

- (void)addTypeDataWithModel:(HWTypeModel *)model {
    if (model) {
        NSString *typeId = [self getGuid];
        if (model.typeId.length > 0) {
            typeId = model.typeId;
        }
        
        model.typeId = typeId;
        
        NSDictionary *dic = model.mj_keyValues;
        [self.store putObject:dic withId:typeId intoTable:[NSString stringWithFormat:@"%@_table",@"type"]];
    }
}

#pragma mark - 查询数据

//获取所有数据
- (NSArray *)getTeaArray {
    NSArray *array = [self.store getAllItemsFromTable:[NSString stringWithFormat:@"%@_table",@"tea"]];
    
    //排序
    NSArray *sortArray = [array sortedArrayUsingComparator:^NSComparisonResult(YTKKeyValueItem *item1, YTKKeyValueItem *item2) {
        
        //时间
        //用于格式化NSDate对象
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //设置格式：zzz表示时区
        [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];

        //NSDate转NSString
        NSString *createdTime1 = [dateFormatter stringFromDate:item1.createdTime];
        NSInteger year1 = [createdTime1 integerValue];

        
        //NSDate转NSString
        NSString *createdTime2 = [dateFormatter stringFromDate:item2.createdTime];
        NSInteger year2 = [createdTime2 integerValue];

        if (year1 > year2) { //不使用intValue比较无效
            return NSOrderedDescending;
        } else if (year1 < year2) {
            return NSOrderedAscending;
        } else {
            return NSOrderedSame;//相等
        }
    }];
    
    NSMutableArray *modelAry = [NSMutableArray arrayWithCapacity:10];
    
    [sortArray enumerateObjectsUsingBlock:^(YTKKeyValueItem *item, NSUInteger idx, BOOL * _Nonnull stop) {
        HWTeaModel *model = [HWTeaModel mj_objectWithKeyValues:item.itemObject];
        [modelAry addObject:model];
    }];
    return modelAry;
}

//获取所有数据
- (NSArray *)getTypeArray {
    NSArray *array = [self.store getAllItemsFromTable:[NSString stringWithFormat:@"%@_table",@"type"]];
    
    //排序
    NSArray *sortArray = [array sortedArrayUsingComparator:^NSComparisonResult(YTKKeyValueItem *item1, YTKKeyValueItem *item2) {
        
        //时间
        //用于格式化NSDate对象
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //设置格式：zzz表示时区
        [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];

        //NSDate转NSString
        NSString *createdTime1 = [dateFormatter stringFromDate:item1.createdTime];
        NSInteger year1 = [createdTime1 integerValue];

        
        //NSDate转NSString
        NSString *createdTime2 = [dateFormatter stringFromDate:item2.createdTime];
        NSInteger year2 = [createdTime2 integerValue];

        if (year1 > year2) { //不使用intValue比较无效
            return NSOrderedDescending;
        } else if (year1 < year2) {
            return NSOrderedAscending;
        } else {
            return NSOrderedSame;//相等
        }
    }];
    
    NSMutableArray *modelAry = [NSMutableArray arrayWithCapacity:10];
    __block HWTypeModel *cusmodel;
    [sortArray enumerateObjectsUsingBlock:^(YTKKeyValueItem *item, NSUInteger idx, BOOL * _Nonnull stop) {
        HWTypeModel *model = [HWTypeModel mj_objectWithKeyValues:item.itemObject];
        if (!model.isCustom && [model.name isEqualToString:@"自定义"]) {
            cusmodel = model;
        } else {
            [modelAry addObject:model];
        }
        
        if (idx + 1 == sortArray.count) {
            [modelAry addObject:cusmodel];
        }
    }];
    return modelAry;
}

//查询指定时间数据
- (HWTeaModel *)querTeaDataDicWithDate:(NSString *)date {
    NSArray *array = [self getTeaArray];
    
    __block HWTeaModel *data = nil;
    
    [array enumerateObjectsUsingBlock:^(HWTeaModel *model, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([date isEqualToString:model.date]) {
            data = model;
        }
    }];
    return data;
}

#pragma mark - 删除

//删除指定id数据
- (void)deleteTeaDataDicWithteaId:(NSString *)teaId {
    NSArray *array = [self getTeaArray];
    
    __block HWTeaModel *data = nil;
    
    [array enumerateObjectsUsingBlock:^(HWTeaModel *model, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([teaId isEqualToString:model.teaId]) {
            data = model;
        }
    }];
    
    
    if (data) {
        [self.store deleteObjectById:data.teaId fromTable:[NSString stringWithFormat:@"%@_table",@"tea"]];
    }
}

#pragma mark - 懒加载

- (YTKKeyValueStore *)store {
    if (!_store) {
        _store = [[YTKKeyValueStore alloc] initDBWithName:[NSString stringWithFormat:@"%@.db",@"HuaWan"]];
    }
    return _store;
}

@end
